package hzfq.region.util;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;

import hzfq.region.domain.City;
import hzfq.region.domain.Province;
import hzfq.region.domain.Region;

/**
 * Created by huzhifengqing@gmail.com since 2018年8月29日 下午7:35:38.
 */
public class RegionParser {

	public static void parseRegion(File file) throws Exception {
		List<Province> provinces = new ArrayList<>();
		RandomAccessFile accessFile = new RandomAccessFile(file, "r");
		String line = null;
		String last = null;
		Integer current = 0;
		while ((line = accessFile.readLine()) != null) {
			line = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
			Integer code = Integer.valueOf(line.substring(0, 6));
			if (code % 10000 == 0) { // 省
				Province province = new Province();
				province.setCode(code);
				province.setProvince(line.substring(7));
				province.setCities(new ArrayList<>());
				provinces.add(province);
				current++;
			} else if (code % 100 == 0) { // 地级市
				Province province = provinces.get(current - 1);
				City city = new City();
				city.setCode(code);
				city.setCity(line.substring(7));
				city.setRegions(new ArrayList<>());
				province.getCities().add(city);
			} else { // 区县
				Integer lastCode = Integer.valueOf(last.substring(0, 6));
				if (lastCode % 10000 == 0) { // 直辖市下属第一个区县
					Province province = provinces.get(current - 1);
					City city = new City();
					city.setCode(province.getCode());
					city.setCity(province.getProvince()); // 直辖市
					List<Region> regions = new ArrayList<>();
					Region region = new Region(code, line.substring(7));
					regions.add(region);
					city.setRegions(regions);
					province.getCities().add(city);
				} else { // 其他区县
					Province province = provinces.get(current - 1);
					List<City> cities = province.getCities();
					Integer citySize = cities.size();
					City city = cities.get(citySize - 1);
					List<Region> regions = city.getRegions();
					regions.add(new Region(code, line.substring(7)));
					city.setRegions(regions);
					cities.set(citySize - 1, city);
					province.setCities(cities);
					provinces.set(current - 1, province);
				}
			}
			last = line;
		}
		accessFile.close();
		System.out.println(JSON.toJSONString(provinces));
	}
}
